<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body>
<div id="app"></div>
<script>
  function sleep(duration) {
    const start = Date.now()
    while (start + duration > Date.now()) {
      // do nothing
    }
  }

  const works = [
    () => {
      console.log(`第1个任务开始`)
      sleep(0)
      console.log('第1个任务结束')
    },
    () => {
      console.log(`第2个任务开始`)
      sleep(0)
      console.log('第2个任务结束')
    },
    () => {
      console.log(`第3个任务开始`)
      sleep(0)
      console.log('第3个任务结束')
    }
  ]

  requestIdleCallback(workLoop);
  function workLoop(deadline) {
    console.log('本帧剩余时间', parseInt(deadline.timeRemaining()));
    while ((deadline.timeRemaining() > 1 || deadline.didTimeout) && works.length > 0) {
      performUnitOfWork();
    }

    if (works.length > 0) {
      console.log(`只剩下${parseInt(deadline.timeRemaining())}ms,时间片到了等待下次空闲时间的调度`);
      requestIdleCallback(workLoop);
    }
  }

  function performUnitOfWork() {
    works.shift()();
  }
</script>
</body>
</html>l
